package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.entity.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class OAuthController {

    @Autowired
    MemberFeignService memberFeignService;

    //http://gulimall.com/oauth/login/success
    @RequestMapping("/oauth/login/success")
    public String weiboLogin(@RequestParam("code") String code, HttpSession session) throws Exception {

        //https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE
        //2347378444
//        App Secret：a9a0d71dc913d37c21acce74cdc9d5d8
//http://gulimall.com/auth_wb/login/success

        Map<String,String> headers = new HashMap<>();
        Map<String,String> querys = new HashMap<>();

        Map<String,String> body = new HashMap<>();
        body.put("client_id","2347378444");
        body.put("client_secret","a9a0d71dc913d37c21acce74cdc9d5d8");
        body.put("grant_type","authorization_code");
        body.put("redirect_uri","http://auth.gulimall.com/oauth/login/success");
        body.put("code",code);

        HttpResponse response = HttpUtils.doPost(
                "https://api.weibo.com",
                "/oauth2/access_token",
                "post",
                headers,
                querys,
                body);

        //处理结果
        if (response.getStatusLine().getStatusCode() == 200){
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            //如果是第一次登录，自动注册
            //不是第一次，查询用户信息返回
            R login = memberFeignService.oauthLogin(socialUser);
            if (login.getCode() == 0){
                MemberResponseVo data = login.getData(new TypeReference<MemberResponseVo>() {
                });

                //分布式系统性session的问题，使用springSession来解决以下两个问题
                //1。跨域问题->扩大域名，指定域名为父域名，默认为自身域名->自定义session
                //自定义CookieSerializer
                //2。多台服务session共享问题
                //3.使用json的序列化方式来存储对象数据到redis->自定义session
                /**
                 * 1。导入依赖
                 * spring-session-data-redis
                 * 2。配置保存类型为redis
                 * spring:
                 *   session:
                 *     store-type: redis
                 * 3.配置redis连接信息
                 * 4.配置session过期时间
                 * server:
                 *   servlet:
                 *     session:
                 *       timeout: 30m
                 * 5.在启动类上开启httpSession功能
                 * @EnableRedisHttpSession
                 */
                session.setAttribute(AuthConstant.LOGIN_USER,data);
                log.info("data:"+data);
                return "redirect:http://gulimall.com/";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
